<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\controller;

use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\CampusLists;
use app\adminapi\logic\CampusLogic;
use app\adminapi\validate\CampusValidate;
use app\common\model\Building;
use app\common\model\Campus;
use app\common\model\Config;
use app\common\model\room\department\RoomDepartment;
use think\facade\Db;

/**
 * 院区控制器
 * Class CampusController
 * @package app\adminapi\controller
 */
class CampusController extends BaseAdminController {


    /**
     * @notes 获取院区列表
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/24 11:07
     */
    public function lists() {
        return $this->dataLists(new CampusLists());
    }


    /**
     * @notes 添加院区
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/24 11:07
     */
    public function add() {
        $params = (new CampusValidate())->post()->goCheck('add');
        $result = CampusLogic::add($params);
        if (true === $result) {
            return $this->success('添加成功', [], 1, 1);
        }
        return $this->fail(CampusLogic::getError());
    }


    /**
     * @notes 编辑院区
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/24 11:07
     */
    public function edit() {
        $params = (new CampusValidate())->post()->goCheck('edit');
        $result = CampusLogic::edit($params);
        if (true === $result) {
            return $this->success('编辑成功', [], 1, 1);
        }
        return $this->fail(CampusLogic::getError());
    }


    /**
     * @notes 删除院区
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/24 11:07
     */
    public function delete() {
        $params = (new CampusValidate())->post()->goCheck('delete');
        CampusLogic::delete($params);
        return $this->success('删除成功', [], 1, 1);
    }


    /**
     * @notes 获取院区详情
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/24 11:07
     */
    public function detail() {
        $params = (new CampusValidate())->goCheck('detail');
        $result = CampusLogic::detail($params);
        return $this->data($result);
    }


    /**
     * @notes 获取楼栋选择
     */
    public function selectBuilding() {
        $result = [];
        $campus = Campus::where('status', 1)->with('buildings')->order('id', 'ASC')->select()->toArray();
        foreach ($campus as $item) {
            $children = [];
            if (!empty($item['buildings'])) {
                foreach ($item['buildings'] as $building) {
                    $children[] = [
                        'value' => $building['id'],
                        'label' => $building['name'],
                        'children' => []
                    ];
                }
            }
            $result[] = [
                'value' => $item['id'],
                'label' => $item['name'],
                'children' => $children
            ];
        }
        return $this->data($result);
    }

    /**
     * @notes 获取全院房间选择
     */
    public function selectRoomHospital() {
        $result = [];
        $campus = Campus::where('status', 1)->with('roomHospitals')->order('id', 'ASC')->select()->toArray();
        foreach ($campus as $item) {
            $children = [];
            if (!empty($item['roomHospitals'])) {
                foreach ($item['roomHospitals'] as $building) {
                    $children_c = [];
                    if (!empty($building['roomHospitals'])) {
                        foreach ($building['roomHospitals'] as $brh_val) {
                            $children_c[] = [
                                'value' => $brh_val['id'],
                                'label' => $brh_val['name'],
                                'children' => []
                            ];
                        }
                    }
                    $children[] = [
                        'value' => $building['id'],
                        'label' => $building['name'],
                        'children' => $children_c,
                        'disabled' => count($children_c) <= 0
                    ];
                }
            }
            $result[] = [
                'value' => $item['id'],
                'label' => $item['name'],
                'children' => $children
            ];
        }
        return $this->data($result);
    }

    /**
     * @notes 获取全院房间选择
     */
    public function selectRoomApartment() {
        $result = [];
        $campus = Campus::where('status', 1)->with('roomApartments')->order('id', 'ASC')->select()->toArray();
        foreach ($campus as $item) {
            $children = [];
            if (!empty($item['roomApartments'])) {
                foreach ($item['roomApartments'] as $building) {
                    $children_c = [];
                    if (!empty($building['roomApartments'])) {
                        foreach ($building['roomApartments'] as $brh_val) {
                            $children_c[] = [
                                'value' => $brh_val['id'],
                                'label' => $brh_val['name'],
                                'children' => []
                            ];
                        }
                    }
                    $children[] = [
                        'value' => $building['id'],
                        'label' => $building['name'],
                        'children' => $children_c,
                        'disabled' => count($children_c) <= 0
                    ];
                }
            }
            $result[] = [
                'value' => $item['id'],
                'label' => $item['name'],
                'children' => $children
            ];
        }
        return $this->data($result);
    }

    /**
     * @notes 获取楼栋选择
     */
    public function selectDevice() {
        $result = [];
        $campus = Campus::where('status', 1)->with('devices')->order('id', 'ASC')->select()->toArray();
        foreach ($campus as $item) {
            $children = [];
            if (!empty($item['devices'])) {
                foreach ($item['devices'] as $building) {
                    $children[] = [
                        'value' => $building['id'],
                        'label' => $building['name'],
                        'children' => []
                    ];
                }
            }
            $result[] = [
                'value' => $item['id'],
                'label' => $item['name'],
                'children' => $children
            ];
        }
        return $this->data($result);
    }

    public function data_control() {
        $cid = $this->adminCid;

        $c_where = [];
        $c_where[] = ["status", "=", 1];
        if ($cid !== 0) {
            $c_where[] = ["id", "=", $cid];
        }

        $b_where = [];
        $b_where[] = ["status", "=", 1];
        if ($cid !== 0) {
            $b_where[] = ["cid", "=", $cid];
        }

        $data = [
            "cb_lists" => Campus::field([
                "id", "name",
                "id as value",
                "name as label",
            ])->where($c_where)->with(["building" => function ($q) {
                $q->field([
                    "id", "name", "cid", "id as value", "name as label",
                ]);
            }])->select()->each(function ($item) {
                $item->children = $item['building'];
                unset($item['building']);
                return $item;
            })->toArray(),
            "campus_list" => Campus::where($c_where)->select()->toArray(),
            "building_list" => Building::where($b_where)->select()->toArray(),
            "type_list" => [
                ["name" => "住户", "model" => "room_hospital_device"],
                ["name" => "公寓", "model" => "room_apartment_device"],
                ["name" => "科室", "model" => "room_department_device"],
            ],
            "department_list" => RoomDepartment::where([
                "status" => 1
            ])->select()->toArray(),
            "room_data" => Config::get_room_data(),
        ];
        return $this->data($data);
    }

    public function data_set() {
        $param = $this->request->param();

        $param['cid'] = $param['cb_ids'][0] ?? 0;
        $param['bid'] = $param['cb_ids'][1] ?? 0;

        if (!isset($param['cid']) || $param['cid'] == '' || $param['cid'] == 0) {
            return $this->fail("请选择院区/楼栋");
        }
        if (!isset($param['room_type']) || $param['room_type'] == '') {
            return $this->fail("请选择分类");
        }
        if (!isset($param['set_data']) || $param['set_data'] == '') {
            return $this->fail("请输入需修改数");
        }

        $where = [];
        if ($param['cid'] > 0) {
            $where[] = ["cid", "=", $param['cid']];
        }
        if ($param['bid'] > 0) {
            $where[] = ["bid", "=", $param['bid']];
        }
        if (in_array($param['device_type'], [1, 2])) {
            $where[] = ["device_type", "in", [0, $param['device_type']]];
        }

        $db = new \think\Db();
        foreach ($param['room_type'] as $room) {
            Db::name($room)->where($where)->update([
                $param['set_type'] => $param['set_data'],
            ]);
            Db::name($room)->where($where)->update([
                "use_total" => $db->raw("reading - base_number"),
                "total_fee" => $db->raw("((reading - base_number) * coefficient * price)"), //  + lift_fee + second_pressure_fee
            ]);

            $config_type = "";
            if ($room == 'room_hospital_device') {
                $config_type = "room_hospital";
            } elseif ($room == 'room_apartment_device') {
                $config_type = "room_apartment";
            } elseif ($room == 'room_department_device') {
                $config_type = "room_department";
            }
            $where = [];
            $where[] = ["type", "=", $config_type];

            if ($param['device_type'] == 1) {
                $where[] = ["name", "=", "s_device_" . $param['set_type']];
            } elseif ($param['device_type'] == 2) {
                $where[] = ["name", "=", "d_device_" . $param['set_type']];
            } else {
                $where[] = ["name", "like", "%" . "device_" . $param['set_type'] . "%"];
            }
            Db::name("config")->where($where)->update([
                "value" => $param['set_data'],
            ]);
        }

        return $this->success('操作成功', [], 1, 1);
    }


    public function quick_set() {
        $param = $this->request->param();
        foreach ($param as $val_1) {
            foreach ($val_1 as $val_2) {
                foreach ($val_2 as $room) {
                    Config::where("type", $room['type'])->where("name", $room['name'])->save([
                        "value" => $room['value'],
                    ]);
                }
            }
        }
        return $this->success('操作成功', [], 1, 1);
    }

}

